import BaseForm, {
  BaseFormSelect,
  BaseFormText,
  BaseFormTextArea,
  BaseModalForm
} from '@/components/base/BaseForm';
import { ModalFC } from '@/components/base/BaseModal';
import BaseTree from '@/components/base/BaseTree';
import { getRadarTreeNoDoList } from '@/pages/radar/RadarInfo/api';
import { isEmpty } from '@/utils/is';
import { useRequest } from '@/utils/request';
import { Col, FormInstance, Row, Spin } from 'antd';
import { useRef, useState } from 'react';
import { EnsureBaseModel } from '../../data';
import { getList as getTaskLevelList } from '../../TaskLevel/api';
import { getList as getTDList } from '../../TechnicalDocumentation/api';
import { addInfo, editInfo } from '../api';

const flatten = (list: Record<string, any>[] = [], parentIds: string[]) => {
  list.forEach((item: any) => {
    item.allId = parentIds.length > 0 ? `${parentIds.join('-')}-${item.id}` : item.id;
    if (item.children) {
      flatten(item.children, [...parentIds, item.id]);
    }
  });
  return list;
};
const InfoModal: ModalFC<{ data?: EnsureBaseModel }> = (props) => {
  const { data = { cycle: 0 } as EnsureBaseModel, onSuccess, ...anyProps } = props;
  const { id, raExtensionId, raSystemId, keyPartsModelId } = data;
  const isadd = isEmpty(id);

  const [key, setKey] = useState(() =>
    [raSystemId, raExtensionId, keyPartsModelId].filter((i) => i).join('-')
  );
  const tree = useRequest(getRadarTreeNoDoList);
  const formRef = useRef<FormInstance>();
  return (
    <BaseModalForm<EnsureBaseModel>
      title='保障基础信息'
      labelCol={{ style: { width: 80 } }}
      width={720}
      formRef={formRef}
      initialValues={{ ...data, allId: key }}
      {...anyProps}
      onFinish={async (values) => {
        values.id = id;
        const [raSystemId, raExtensionId = '', keyPartsModelId = ''] = key.split('-');
        values.raSystemId = raSystemId;
        values.raExtensionId = raExtensionId;
        values.keyPartsModelId = keyPartsModelId;
        const { ok } = await (isadd ? addInfo : editInfo)(values);
        ok && onSuccess && onSuccess();
        return ok;
      }}
    >
      <Row>
        <Col span={12}>
          <BaseForm.Item
            name='allId'
            label='雷达结构'
            rules={[{ required: true, message: '请选择雷达结构' }]}
          >
            <Spin spinning={tree.loading}>
              <BaseTree
                blockNode
                defaultExpandAll
                height={400}
                defaultSelectedKeys={[key]}
                bindProps={{ key: 'allId', value: 'allId', title: 'name' }}
                treeData={flatten(tree.data, [])}
                onSelect={(keys, { node }) => {
                  const { allId } = node as unknown as Record<string, string>;
                  setKey(allId);
                  const value = formRef.current?.getFieldsValue(true);
                  formRef.current?.setFieldsValue({ ...value, allId });
                }}
              />
            </Spin>
          </BaseForm.Item>
        </Col>
        <Col span={12}>
          <BaseFormSelect
            label='任务级别'
            name='taskLevelId'
            request={getTaskLevelList}
            fieldProps={{
              defaultSelectedOptions: [{ name: data.taskLevelName, id: data.taskLevelId }],
              fieldNames: { label: 'name', value: 'id' }
            }}
            placeholder='请选择任务级别'
            rules={[{ required: true, message: '请选择任务级别' }]}
          />
          <BaseFormText
            label='保障名称'
            name='name'
            placeholder='请输入保障名称'
            fieldProps={{ maxLength: 20, showCount: true }}
            rules={[
              { required: true, message: '请输入保障名称' },
              { type: 'string', max: 20, message: '长度不可超过20位' }
            ]}
          />
          <BaseFormSelect
            label='保障工卡'
            name='documentId'
            request={getTDList}
            fieldProps={{
              defaultSelectedOptions: [{ name: data.documentName, id: data.documentId }],
              fieldNames: { label: 'name', value: 'id' }
            }}
            placeholder='请选择保障工卡'
            rules={[{ required: true, message: '请选择保障工卡' }]}
          />
          <BaseFormTextArea
            fieldProps={{ maxLength: 240, showCount: true }}
            label='内容'
            name='content'
            placeholder='请输入保障内容'
          />
        </Col>
      </Row>
    </BaseModalForm>
  );
};

export default InfoModal;
